package com.duoduo.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO
 *
 * @author qian
 * @version 1.0
 * @date 2020/11/21 12:32
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    private int getAndIncrement() {
        int current, next;
        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : (current + 1);
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("第几次访问，次数next:" + next);
        return next;
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
